#!/bin/bash

# 设置错误时退出
set -e

# 设置配置主目录
if [ -z "$CONFIG_HOME" ]; then
  export CONFIG_HOME="${HOME}/.mac_sync"
fi

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}===== 开始设置开发环境配置 =====${NC}"

# 确定目录路径
MAC_SYNC_DIR="$CONFIG_HOME"
BACKUP_DIR="$MAC_SYNC_DIR/backup/config_$(date +%Y%m%d_%H%M%S)"

# 创建备份目录
mkdir -p "$BACKUP_DIR"

# 备份当前配置文件
echo -e "${YELLOW}备份当前配置文件...${NC}"
for file in .zshrc .zprofile .mac_env.zsh; do
  if [ -f "$HOME/$file" ]; then
    echo "备份 $HOME/$file 到 $BACKUP_DIR"
    cp "$HOME/$file" "$BACKUP_DIR/"
  fi
done
echo -e "${GREEN}✓ 备份完成${NC}"

# 创建符号链接
echo -e "${YELLOW}设置 mac_env.zsh 链接...${NC}"
if [ -f "$HOME/.mac_env.zsh" ]; then
  echo "移除现有的 .mac_env.zsh 文件"
  rm "$HOME/.mac_env.zsh"
fi

echo "创建从 $MAC_SYNC_DIR/mac_env.zsh 到 $HOME/.mac_env.zsh 的链接"
ln -sf "$MAC_SYNC_DIR/mac_env.zsh" "$HOME/.mac_env.zsh"
echo -e "${GREEN}✓ 链接创建完成${NC}"

# 检查是否有必要的目录
echo -e "${YELLOW}检查必要的目录...${NC}"
for dir in "$HOME/.n" "$HOME/.node_global" "$HOME/.node_global/legacy/npm/bin" "$HOME/.node_global/legacy/pnpm/bin" "$HOME/.node_global/legacy/pnpm/store" "$HOME/.node_global/middle/npm/bin" "$HOME/.node_global/middle/pnpm/bin" "$HOME/.node_global/middle/pnpm/store" "$HOME/.node_global/modern/npm/bin" "$HOME/.node_global/modern/pnpm/bin" "$HOME/.node_global/modern/pnpm/store"; do
  if [ ! -d "$dir" ]; then
    echo "创建目录: $dir"
    mkdir -p "$dir"
    chmod 755 "$dir"
  fi
done
echo -e "${GREEN}✓ 目录检查完成${NC}"

# 修改 .zshrc
echo -e "${YELLOW}更新 .zshrc...${NC}"
# 检查是否已经包含 source ~/.mac_env.zsh
if ! grep -q "source ~/.mac_env.zsh" "$HOME/.zshrc" 2>/dev/null; then
  # 创建清理后的 .zshrc
  echo "从备份创建清理后的 .zshrc"
  
  # 提取不包含环境变量和别名的部分
  grep -v "N_PREFIX\|npm\|pnpm\|NODE_GLOBAL_ROOT\|alias ni\|alias nd\|alias ns\|alias nb\|alias p\|ws=\"\|vs=\"" "$BACKUP_DIR/.zshrc" > "$HOME/.zshrc.new"
  
  # 添加加载 mac_env.zsh 的命令
  echo -e "\n# Load development environment configuration" >> "$HOME/.zshrc.new"
  echo "export CONFIG_HOME=\"\$HOME/.mac_sync\"" >> "$HOME/.zshrc.new"
  echo "source ~/.mac_env.zsh" >> "$HOME/.zshrc.new"
  
  # 替换原文件
  mv "$HOME/.zshrc.new" "$HOME/.zshrc"
  echo -e "${GREEN}✓ .zshrc 已更新${NC}"
else
  echo ".zshrc 已包含对 mac_env.zsh 的引用，无需修改"
fi

# 显示完成信息
echo -e "${BLUE}===== 环境配置设置完成 =====${NC}"
echo -e "${YELLOW}请运行以下命令使配置生效：${NC}"
echo -e "${GREEN}source ~/.zshrc${NC}"
echo -e "${YELLOW}您的原始配置已备份到：${NC} ${BLUE}$BACKUP_DIR${NC}" 